package com.lin.controller;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.StandardCharsets;

@RequestMapping("/demo5")
@Controller
public class Demo5 {

    @Value("${queue.demo5_exchange_name}")
    public String EXCHANGE_NAME;
    /*
     *  topic 就是相当于正则匹配了
     *  让消息可以匹配一系列的队列
     *  主题格式为 word1.word2.word3.#/*   #表示匹配0个或者多个单词 *表示匹配一个单词
     *  主题的大小最大为 255 bytes
     */

    // localhost:8080/demo5/send/*.lin.*.*
    @RequestMapping("/send/{topic}")
    @ResponseBody
    public String send(@PathVariable String topic) {
        try(
                Connection connection = RabbitUtil.getConnection();
                Channel channel = connection.createChannel();
                ) {
            channel.exchangeDeclare(EXCHANGE_NAME,"topic");
            String message = "你在凝视深渊的时候，深渊也在凝视你";
            System.out.println(topic);
            channel.basicPublish(EXCHANGE_NAME,topic, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "已经成功发送消息到对应主题";
    }

}
